# -*- coding: utf-8 -*-
# Created by shu2015626 on 2019-7-12
"""
获取主机ip地址
"""

import socket
import logging

logger = logging.getLogger("py_timed_tasks")


def get_host_ip_by_internet() -> str:
    """
    查询主机ip地址。联网的情况下可用
    :return: 主机ip
    :rtype `str`
    """
    ip = None
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    except Exception as e:
        logger.error('获取主机ip失败')
    finally:
        s.close()
    return ip


def get_host_ip_by_hostname() -> str:
    """
    查询主机ip地址。联不联网的情况下可用
    :return: 主机ip
    :rtype `str`
    """
    hostname = socket.getfqdn(socket.gethostname())
    ip = socket.gethostbyname(hostname)
    return ip


if __name__ == "__main__":
    print("联网: ", get_host_ip_by_internet())
    print("不联网: ", get_host_ip_by_hostname())